import { playMode } from 'common/js/config';
import { shuffle } from 'common/js/util';
import { mapGetters, mapMutations,mapActions} from 'vuex';
export const playlistMixin = {
  computed: {
    ...mapGetters(['playlist'])
  },
  mounted() {
    this.handlePlaylist(this.playlist)
  },
  activated() {
    this.handlePlaylist(this.playlist)
  },
  watch: {
    playlist(newVal) {
      this.handlePlaylist(this.playlist)
    }
  },
  methods: {
    handlePlaylist() {
      throw new Error('component must implement handlePlaylist method')
    }
  }
}

export const playerMixin = {
  computed: {
    iconMode() {
      return this.mode === playMode.sequence ? 'icon-shunxubofang' : this.mode === playMode.loop ? 'icon-danquxunhuan' : 'icon-suijibofang'
    },
    ...mapGetters(
      ['sequenceList',
        'currentSong',
        'playlist',
        'mode',
        'favoriteList'
      ])
  },
  methods: {
    changeMode() {
      const mode = (this.mode + 1) % 3;
      this.setPlayMode(mode)
      let list = null;
      if (mode === playMode.random) {
        list = shuffle(this.sequenceList)
      } else {
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlayList(list)
    },
    resetCurrentIndex(list) {
      // findIndex 返回符合 function 的 第一个元素位置
      let index = list.findIndex((item) => {
        return item.id === this.currentSong.id
      });
      this.setCurrentIndex(index)
    },
    // 切换 收藏图标
    getFavoriteIcon(song){
     return this.isFavorite(song)? 'icon-love-b':'icon-shoucang'
    },
    // 删除 收藏列表指定song,或者,保存song值至收藏列表
    toggleFavorite(song){
      if(this.isFavorite(song)){
        this.deleteFavoriteList(song)
      }else{
        this.saveFavoriteList(song)
      }
    },
    // 判断 收藏列表 有没有
    isFavorite(song){
      const index=this.favoriteList.findIndex((item)=>{
        return item.id===song.id
      })
      return index>-1
    },
    ...mapMutations({
      setPlayingState: 'SET_PLAYING_STATE',
      setCurrentIndex: 'SET_CURRENT_INDEX',
      setPlayMode: 'SET_PLAY_MODE',
      setPlayList: 'SET_PLAYLIST',
    }),
    ...mapActions(['saveFavoriteList','deleteFavoriteList'])
  }
}

export const searchMixin = {
  data() {
    return {
      query: '',
      refreshDelay:100
    }
  },
  computed: {
    ...mapGetters(
      ['searchHistory']
    )
  },
  methods: {
    // 保存search
    saveSearch() {
      this.setSearchHistory(this.query)
    },
    // set 搜索值
    addquery(query) {
      this.$refs.searchBox.setQuery(query)
    },
    // 删除 delete
    delectOne(item){
      this.delectSearchHistory(item)
    },
    // 移除焦点
    blurInput() {
      this.$refs.searchBox.blur()
    },
    // 修改值
    querychange(query) {
      this.query = query
    },
    ...mapActions([
      'setSearchHistory',
      'delectSearchHistory',
    ])
  },
}
